package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.request.TemplateCreateRequest;
import com.github.permissiondog.cancanpbackend.request.TemplateDeleteRequest;
import com.github.permissiondog.cancanpbackend.request.TemplateModifyRequest;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.TemplateResponse;
import com.github.permissiondog.cancanpbackend.response.TemplatesResponse;
import com.github.permissiondog.cancanpbackend.service.TemplateService;
import org.apache.ibatis.exceptions.PersistenceException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/template")
public class TemplateServlet extends BaseServlet{
    /**
     * 获取审批模板列表
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        var templateIdParam = req.getParameter("templateId");
        if (templateIdParam == null) {
            var templates = TemplateService.getInstance().getTemplates();
            json(res, TemplatesResponse.builder().ok(true).templates(templates).build());
            return;
        }
        int templateId;
        try {
            templateId = Integer.parseInt(templateIdParam);
        } catch (Exception e) {
            json(res, BaseResponse.builder().ok(false).msg("参数错误").build());
            return;
        }

        var template = TemplateService.getInstance().getTemplateById(templateId);
        json(res, TemplateResponse.builder().ok(true).template(template).build());
    }
}
